package com.wms.service.impl;

import com.wms.common.Result;
import com.wms.entity.User;
import com.wms.domain.LoginUser;
import com.wms.service.LoginService;
import com.wms.utils.JwtUtils;
import com.wms.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;


    @Autowired
    private RedisCache redisCache;

    @Override
    public Result login(User user) {
        HashMap res = new HashMap<>();
        //AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getNo(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ajax
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        Map<String,Object> map = new HashMap<>();
        map.put(JwtUtils.DETAILS_USER_ID,userId);
        String token = JwtUtils.createToken(map);
        res.put("token",token);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:"+userId,loginUser);
        return Result.suc(res);
    }

    @Override
    public Result logout() {
        //获取SecirityContextHolder中的用户id
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
//        UsernamePasswordAuthenticationToken authentication =
//                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication.getPrincipal());
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer id = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("login:" + id);
        return Result.suc();
    }
}
